package vote;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.interfaces.RSAPublicKey;
import java.util.LinkedList;
import java.util.List;

import prevote.PreVotePanelDescriptor;
import registration.RegistrationResources;
import util.Utils;
import wizard.WizardPanelDescriptor;
import afterVote.AfterVotePanelDescriptor;

import com.google.common.collect.Lists;

import data.Blind;
import data.VotingSet;

public class VotePanelDescriptor extends WizardPanelDescriptor implements ActionListener
{
    public static String IDENTIFIER = "VOTE_PANEL";
    private VotePanel vp;
    private List<String> candidates;
    private String PKWSignedCard;
    private String _selectedCandidate;
    private static String PKWShamirPublicKeyFile;
    private static String keyStoreFile;
    private static char[] keyStorePassword;
    static
    {
        RegistrationResources resources = new RegistrationResources();
        PKWShamirPublicKeyFile = (String)resources.getObject( "PKWShamirPublicKeyFile" );
        keyStoreFile = (String)resources.getObject( "trustKeyStoreFile" );
    }

    public VotePanelDescriptor()
    {
        vp = new VotePanel();
        setPanelDescriptorIdentifier( IDENTIFIER );
        setPanelComponent( vp );
    }

    public String getNextPanelDescriptor()
    {
        return AfterVotePanelDescriptor.IDENTIFIER;
    }

    public String getBackPanelDescriptor()
    {
        return PreVotePanelDescriptor.IDENTIFIER;
    }

    public void aboutToDisplayPanel()
    {
        getWizard().setBackButtonEnabled( false );
        getWizard().setCancelButtonEnabled( false );
        candidates = (List<String>)getWizard().getPanelData( getBackPanelDescriptor() + "candidates" );
        // List<String> candidates2 = Lists.newLinkedList();
        // candidates = Arrays.asList( candidates.get( 0 ).split( "\r\n" ) );
        List<String> candidatesToShow = new LinkedList<String>();
        PKWSignedCard = (String)getWizard().getPanelData( getBackPanelDescriptor() + "server_message" );
        for( int i = 0; i < candidates.size() - 1; ++i )
        {
            String s = candidates.get( i );
            candidatesToShow.add( s.substring( 0, s.length() - 2 ) );
        }
        List<String> sortedCandidates = Lists.newLinkedList();
        for( int i = 1; i <= candidatesToShow.size(); i++ )
            for( String candidate: candidatesToShow )
                if( candidate.startsWith( "" + i ) )
                    sortedCandidates.add( candidate );
        vp.updateRadioButtons( sortedCandidates );
        vp.addRadioButtonsActionListener( this );
    }

    public void aboutToHidePanel()
    {
        BigInteger blindParameter = (BigInteger)getWizard().getPanelData( getBackPanelDescriptor() + "blind_parameter" );
        int randomServerNumber = (Integer)getWizard().getPanelData( getBackPanelDescriptor() + "random_number" );
        List<VotingSet> sets = (List<VotingSet>)getWizard().getPanelData( getBackPanelDescriptor() + "sets" );
        Blind b = new Blind();
        try
        {
            RSAPublicKey PKWShamirPublicKey = (RSAPublicKey)Utils.readPublicKey( PKWShamirPublicKeyFile );
            KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
            FileInputStream fis = new FileInputStream( keyStoreFile );
            ks.load( fis, "".toCharArray() );
            RSAPublicKey PKWPublicKey = (RSAPublicKey)ks.getCertificate( "PKW" ).getPublicKey();
            PKWSignedCard = b.unblind( PKWSignedCard, PKWPublicKey, blindParameter );
            VotingSet normalSelectedSet = sets.get( randomServerNumber );
            int candidateNumber = normalSelectedSet.getVoteNumber( getSelectedCandidate() );
            String selectedVote = b.pickCard( PKWSignedCard, candidateNumber );
            String voteToSend = b.SecHash( selectedVote, PKWShamirPublicKey );
            getWizard().storePanelData( IDENTIFIER + "voteToSend", voteToSend );
            try
            {
                Thread.sleep( 100 );
            }
            catch( InterruptedException e )
            {
            }
            getWizard().storePanelData( IDENTIFIER + "PKWSignedCard", PKWSignedCard );
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
        catch( KeyStoreException e )
        {
            // TODO Auto-generated catch block
            throw new RuntimeException( e );
        }
        catch( NoSuchAlgorithmException e )
        {
            // TODO Auto-generated catch block
            throw new RuntimeException( e );
        }
        catch( CertificateException e )
        {
            // TODO Auto-generated catch block
            throw new RuntimeException( e );
        }
    }

    @Override
    public void actionPerformed( ActionEvent arg0 )
    {
        getWizard().setNextFinishButtonEnabled( true );
        _selectedCandidate = vp.getSelectedButton();
        System.out.println( _selectedCandidate );
    }

    public String getSelectedCandidate()
    {
        return _selectedCandidate;
    }
}
